package org.summer.lawyer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.summer.common.core.constant.Constants;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.common.satoken.utils.LoginHelper;
import org.summer.lawyer.domain.BrokerageRecord;
import org.summer.lawyer.domain.bo.brokeragerecord.BrokerageRecordBo;
import org.summer.lawyer.domain.vo.brokeragerecord.BrokerageRecordVo;
import org.summer.lawyer.mapper.BrokerageRecordMapper;
import org.summer.lawyer.service.IBrokerageRecordService;
import org.summer.lawyer.util.ParamsUtil;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 佣金记录Service业务层处理
 *
 * @author summer
 * @date 2024-06-25
 */
@RequiredArgsConstructor
@Service
public class BrokerageRecordServiceImpl extends ServiceImpl<BrokerageRecordMapper, BrokerageRecord> implements IBrokerageRecordService {


    /**
     * 查询佣金记录
     *
     * @param id 主键
     * @return 佣金记录
     */
    @Override
    public BrokerageRecordVo selectBrokerageRecordVoById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询佣金记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 佣金记录分页列表
     */
    @Override
    public TableDataInfo<BrokerageRecordVo> selectPageList(BrokerageRecordBo bo, PageQuery pageQuery) {
        QueryWrapper<BrokerageRecordBo> lqw = buildQueryWrapper(bo);
        Page<BrokerageRecordVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的佣金记录列表
     *
     * @param bo 查询条件
     * @return 佣金记录列表
     */
    @Override
    public List<BrokerageRecordVo> selectBrokerageRecordVoList(BrokerageRecordBo bo) {
        QueryWrapper<BrokerageRecordBo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectBrokerageRecordVoList(lqw);
    }

    private QueryWrapper<BrokerageRecordBo> buildQueryWrapper(BrokerageRecordBo bo) {
        Map<String, Object> params = ParamsUtil.getParams(bo.getParams());
        QueryWrapper<BrokerageRecordBo> lqw = Wrappers.query();
        lqw.eq("br.del_flag", Constants.DEL_FLAG_NOT_DEL);
        lqw.eq(bo.getWxUserId() != null, "br.wx_user_id", bo.getWxUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getBizId()), "br.biz_id", bo.getBizId());
        lqw.eq(StrUtil.isNotBlank(bo.getBizType()), "br.biz_type", bo.getBizType());
        lqw.like(StrUtil.isNotBlank(bo.getTitle()), "br.title", bo.getTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), "br.status", bo.getStatus());
        lqw.like(StrUtil.isNotBlank(bo.getNickname()), "bu.nickname", bo.getNickname());
        lqw.like(StrUtil.isNotBlank(bo.getSourceUserName()), "br.source_user_name", bo.getSourceUserName());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,"br.create_time",params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc("br.id");
        return lqw;
    }

    /**
     * 新增佣金记录
     *
     * @param bo 佣金记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BrokerageRecordBo bo) {
        BrokerageRecord add = MapstructUtils.convert(bo, BrokerageRecord.class);
        validEntityBeforeSave(add);
        add.setUpdateTime(DateUtil.date());
        if(LoginHelper.getLoginUser() != null){
            add.setCreateBy(LoginHelper.getUserId());
            add.setUpdateBy(LoginHelper.getUserId());
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改佣金记录
     *
     * @param bo 佣金记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BrokerageRecordBo bo) {
        BrokerageRecord update = MapstructUtils.convert(bo, BrokerageRecord.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtil.date());
        if(LoginHelper.getUserId() != null){
            update.setUpdateBy(LoginHelper.getUserId());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BrokerageRecord entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除佣金记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Long selectTotalAmountByDay(Date day) {
        return selectTotalAmountByDay(null,day);
    }

    @Override
    public Long selectTotalAmountByDay(Long wxUserId, Date day) {
        Date beginTime = DateUtil.beginOfDay(day);
        Date endTime = DateUtil.endOfDay(day);
        LambdaQueryWrapper<BrokerageRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(wxUserId != null, BrokerageRecord::getWxUserId, wxUserId);
        lqw.between(BrokerageRecord::getUnfreezeTime, beginTime, endTime);
        lqw.eq(BrokerageRecord::getStatus, "1");
        List<BrokerageRecordVo> list = baseMapper.selectVoList(lqw);
        if(CollUtil.isNotEmpty(list)){
            return list.stream().mapToLong(BrokerageRecordVo::getAmount).sum();
        }
        return 0L;
    }

    @Override
    public List<BrokerageRecordVo> selectCommissionRecord(BrokerageRecordBo bo) {
        LambdaQueryWrapper<BrokerageRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(BrokerageRecord::getStatus, "0");
        lqw.eq(BrokerageRecord::getDelFlag, Constants.DEL_FLAG_NOT_DEL);
        lqw.le(BrokerageRecord::getUnfreezeTime,bo.getUnfreezeTime());
        return baseMapper.selectVoList(lqw);
    }
}
